
const CHAT = {
  
  ws: Object,
  opened:false,
  tag:true,
  userinfo:null,
  contacts:[],
  chatOpen:[],
  log:[],
  isProject:0,
  reciveId:0,
  project:[],
  unread:[],
  notify:[],
  unreadCount:0,
  notifyCount:0,
  timer:null,
  showLoding:false,
  init: function () {
    var domain = window.location.host;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
      //CHAT.ws = new WebSocket("ws://"+domain+"/teacherwebsocket?token=" + window.localStorage.getItem("token") + "&classId=" + CHAT.courseArrange.id);
      CHAT.ws = new WebSocket("ws://123.206.109.240/websocket?token=" + window.localStorage.getItem("token")+"&type=web");
      CHAT.ws.onopen = function (evt) {
        bus.$notify({
          title: '提示',
          message: '安全中心已开启！',
          type: 'success'
        });
        CHAT.opened = true;
        CHAT.tag = true;
        CHAT.timer && clearInterval(CHAT.timer);
        CHAT.timer = setInterval(()=>{
          if(CHAT.opened){ 
            if(!CHAT.tag){
              bus.$notify({
                title: '警告',
                message: '安全中心已关闭！正在重连',
                type: 'warning'
              });
              CHAT.timer && clearInterval(CHAT.timer);
              CHAT.ws = new WebSocket("ws://123.206.109.240/websocket?token=" + window.localStorage.getItem("token") +"&type=app");
            }else{
              CHAT.tag = false;
              CHAT.submit({
                status:200,
                message:null,
                result:null
              })
            }
          }else{
            CHAT.timer && clearInterval(CHAT.timer);
          }
        },5000);
      };
      CHAT.ws.onclose = function (evt) {
      };
      CHAT.ws.onmessage = function (evt) {
        let data = JSON.parse(evt.data);
        switch (data.status) {
          case 200:
            CHAT.tag = true;
            break;
          case 1:
            CHAT.contacts = data.result;
            break;
          case 2:
            CHAT.chatOpen = data.result;
            
            CHAT.reciveId = 0;
            if(CHAT.chatOpen.length != 0){
              CHAT.log = CHAT.chatOpen[0].log;
              CHAT.isProject = CHAT.chatOpen[0].isProject;
              CHAT.reciveId = CHAT.chatOpen[0].contactId;
            }
            CHAT.chatOpen.forEach(element => {
              element.log = element.log.reverse();
            });
            setTimeout(() => {
              var div = document.getElementById('scrolldIV');
              div.scrollTop = div.scrollHeight;
            }, 5000);
            
            break;
          case 3:
            let a = true;
            data.result.gmtCreate = new Date().getTime();
            if(data.message == "0"){
              CHAT.chatOpen.forEach(e => {
                if(e.contactId == data.result.contactId){
                  a = false;
                  e.log.push(data.result)
                }
              })
            }else{
              if(data.result.isProject == 0){
                CHAT.chatOpen.forEach(e => {
                  if(e.contactId == data.result.sendId){
                    a = false;
                    if(CHAT.reciveId != e.contactId){CHAT.unreadCount++;e.unread ++;}
                    e.log.push(data.result)
                  }
                });
              }else{
                CHAT.chatOpen.forEach(e => {
                  if(e.contactId == data.result.contactId){
                    a = false;
                    if(CHAT.reciveId != e.contactId){CHAT.unreadCount++;e.unread ++;}
                    e.log.push(data.result)
                  }
                });
              }
             
              if(a){
                CHAT.submit({
                  status:4,
                  message:data.result.isProject,
                  result:data.result.isProject==0?(data.result.sendId):(data.result.contactId)
                })
              }
            }
            
            break;
          case 4:
           
            data.result.unread = 1;
            for(var key in CHAT.unread){
              if(key == data.result.contactId){
                data.result.unread = CHAT.unread[key];
              }
            }
            CHAT.chatOpen.push(data.result)
            break;
          case 5:
            let temp = [];
            CHAT.chatOpen.forEach(e => {
              if(e.contactId != data.result){temp.push(e);}
            });
            CHAT.chatOpen = temp;
            if(CHAT.chatOpen.length != 0){
              CHAT.log = CHAT.chatOpen[0].log;
              CHAT.reciveId = CHAT.chatOpen[0].contactId;
            }else{
              CHAT.log = [];
              CHAT.reciveId = 0;
            }
            break;
          case 6:
            if(data.result != null){
              CHAT.unread = data.result[key];
              for(var key in data.result){
                let a = true;
                if(key == 0){
                  CHAT.notifyCount = data.result[key];
                }else{
                  CHAT.unreadCount += data.result[key];
                  CHAT.chatOpen.forEach(e => {
                    if(e.contactId == (key<0?(key*-1):(key))){
                      e.unread = data.result[key];
                      a = false; 
                    }
                  });
                  if(a){
                    CHAT.submit({
                      status:4,
                      message:key<0?(1):(0),
                      result:Number(key<0?(key*-1):(key))
                    })
                  }
                }
              }
            }
            break;
          case 7:
            if(data.result == 0){
              CHAT.notifyCount = 0;
            }else{
              CHAT.unreadCount -= Number(data.message);
              if(CHAT.unreadCount < 0 ){
                CHAT.unreadCount = 0;
              }
              for(var key in CHAT.unread){
                if(data.result ==key){
                  delete CHAT.unread[key];
                }
              }
              CHAT.chatOpen.forEach(e => {
                if(e.contactId == (data.result<0?(data.result*-1):(data.result))){
                  e.unread = 0;
                }
              });
            }
            break;
          case 10:
            CHAT.project = data.result;
            break;
          case 100:
            CHAT.notify = data.result;
            break;
          case 103:
            data.result.gmtCreate = new Date().getTime();
            CHAT.notify.unshift(data.result);
            CHAT.unreadCount++;
            CHAT.notifyCount = CHAT.notifyCount+1;
            break;
          case 300:
            data.result.forEach(e=>{
              CHAT.log.unshift(e);
            })
            CHAT.showLoding = false;
            break;
          case -1:
            bus.$notify({
              title: '警告',
              message: data.message,
              type: 'error'
            });
            CHAT.opened = false;
            clearInterval(CHAT.timer);
            break;
          default:
            break;
        };
        if(data.status == 300 ){
          window.bus.$nextTick(() => {
            var div = document.getElementById('scrolldIV');
            div.scrollTop = 0;
          })
        }else if(data.status != 200 ){
          window.bus.$nextTick(() => {
            var div = document.getElementById('scrolldIV');
            div.scrollTop = div.scrollHeight;
          })
        }
      }
    } else {
      alert('您的浏览器不支持Websocket！更换浏览器继续访问！')
    }

  },

  upload(mess,file){
    var formData = new FormData();
    formData.append('file', file);
    let config = {
      headers: {'Content-Type': 'multipart/form-data'}
    }
    axios.post("http://120.78.95.220:8085/public/upload/chat",formData,config).then(response => {
      if(response.data.status === 1){
        mess.id = 1;
        mess.other = response.data.result;
        CHAT.submit({
          status:3,
          message:null,
          result:mess
        });
      }else{
        mess.id = -1;
      }
      
    }).catch(function (error) {
  　　alert(error);
    });
  },

  submit: function (jsonObject) {
    console.log(jsonObject)
    CHAT.ws.send(JSON.stringify(jsonObject));
  },
  datetimeFormat : function(longTypeDate){ 
    var datetimeType = ""; 
    var date = new Date(); 
    var newdate = new Date(); 
    date.setTime(longTypeDate);
    if(date.getFullYear() === newdate.getFullYear() && date.getMonth() === newdate.getMonth() && date.getDay() === newdate.getDay()){
      datetimeType+= "  " + CHAT.getHours(date);  //时 
      datetimeType+= ":" + CHAT.getMinutes(date);   //分
      datetimeType+= ":" + CHAT.getSeconds(date);   //分
    }else{
      datetimeType+= date.getFullYear();  //年 
      datetimeType+= "-" + CHAT.getMonth(date); //月  
      datetimeType += "-" + CHAT.getDay(date);  //日 
      datetimeType+= "  " + CHAT.getHours(date);  //时 
      datetimeType+= ":" + CHAT.getMinutes(date);   //分
      datetimeType+= ":" + CHAT.getSeconds(date);   //分
    }
    
    return datetimeType;
  },
  datetimeFormat2 : function(longTypeDate){ 
    var datetimeType = ""; 
    var date = new Date(); 
    var newdate = new Date(); 
    date.setTime(longTypeDate);
    if(date.getFullYear() === newdate.getFullYear() && date.getMonth() === newdate.getMonth() && date.getDay() === newdate.getDay()){
      datetimeType+= "  " + CHAT.getHours(date);  //时 
      datetimeType+= ":" + CHAT.getMinutes(date);   //分
      datetimeType+= ":" + CHAT.getSeconds(date);   //分
    }else{
      datetimeType+= date.getFullYear();  //年 
      datetimeType+= "-" + CHAT.getMonth(date); //月  
      datetimeType += "-" + CHAT.getDay(date);  //日 
    }
    
    return datetimeType;
  },
  //返回 01-12 的月份值  
  getMonth: function(date){ 
    var month = ""; 
    month = date.getMonth() + 1; //getMonth()得到的月份是0-11 
    if(month<10){ 
      month = "0" + month; 
    } 
    return month; 
  } ,
  //返回01-30的日期 
  getDay:function (date){ 
    var day = ""; 
    day = date.getDate(); 
    if(day<10){ 
      day = "0" + day; 
    } 
    return day; 
  },
  //返回小时
  getHours:function (date){
    var hours = "";
    hours = date.getHours();
    if(hours<10){ 
      hours = "0" + hours; 
    } 
    return hours; 
  },
  //返回分
  getMinutes:function (date){
    var minute = "";
    minute = date.getMinutes();
    if(minute<10){ 
      minute = "0" + minute; 
    } 
    return minute; 
  },
  //返回秒
  getSeconds:function (date){
    var second = "";
    second = date.getSeconds();
    if(second<10){ 
      second = "0" + second; 
    } 
    return second; 
  }
}
export default CHAT
